//
//  WeightReferenceViewController.m
//  SHHCPhone
//
//  Created by gfsh on 14-6-18.
//  Copyright (c) 2014年 sheng long. All rights reserved.
//

#import "WeightReferenceViewController.h"
#import "MSSimpleGauge.h"
#import "ChartView.h"
#import "GraphView.h"
#import <CoreText/CoreText.h>

#define WEIGHT_REFERENCE_KEY @"weight_reference_key"

@implementation WeightReferenceViewController
{
//    MSSimpleGauge *weightCounter;//体重计
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    navigationBarView.title = @"理想体重参考";
    [navigationBarView setNormalLeftButton];
    //[self initChart];
    [self loadData];
}

#pragma mark 初始化体重计
- (void)initWeightCounter
{
//    weightCounter = [[MSSimpleGauge alloc] initWithFrame:CGRectMake(CURRENT_CONTENT_WIDTH/2-130/2, NAVIGATIONBAR_HEIGHT, 130, 80)];
//    weightCounter.startAngle = 0;
//    weightCounter.endAngle = 180;
//    weightCounter.fillArcFillColor = [UIColor colorWithRed:241.f/255 green:130.f/255 blue:146.f/255 alpha:1.f];
//    weightCounter.fillArcStrokeColor = [UIColor colorWithRed:241.f/255 green:130.f/255 blue:146.f/255 alpha:1.f];
//
//    weightCounter.value = 70;
//    [self.view addSubview:weightCounter];
//    
//    UILabel *weightLab = [[UILabel alloc]initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT+10, CURRENT_CONTENT_WIDTH, 20)];
//    weightLab.textAlignment = NSTextAlignmentCenter;
//    weightLab.textColor = GET_COLOR(@"fe8cb6");
//    weightLab.font = [UIFont systemFontOfSize:12];
//    weightLab.text = @"当前处于孕期，理想体重58KG";
//    [self.view addSubview:weightLab];
}

#pragma mark 初始化孕中图表及相应文字说明
- (void)initChart:(NSArray*)arr
{
    if (!arr) {
        return;
    }
    UIScrollView *sv = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NAVIGATIONBAR_HEIGHT, CURRENT_CONTENT_WIDTH, CURRENT_CONTENT_HEIGHT-NAVIGATIONBAR_HEIGHT)];
    sv.backgroundColor = [UIColor clearColor];
    sv.showsVerticalScrollIndicator = NO;
    [self.view addSubview:sv];
    
    GraphView *gv = [[GraphView alloc]initWithFrame:CGRectMake(10, 10, sv.frame.size.width-20, sv.frame.size.height-160)];
    gv.cellWidth = 40.f;
    gv.cellHeight = (gv.frame.size.height-70)/4;
    gv.title = @"孕期体重增长曲线图";
    gv.titleColor = GET_COLOR(@"3e3e3e");
    [sv addSubview:gv];
    NSDictionary *dic = arr[0];
    NSArray *low = dic[kLow];
    NSArray *middle = dic[kMiddle];
    NSArray *high = dic[kHight];
    
    NSMutableArray *xAsis = [NSMutableArray array];
    NSMutableArray *yAsis = [NSMutableArray array];
    
    NSMutableArray *lowPoints = [NSMutableArray array];
    NSMutableArray *middlePoints = [NSMutableArray array];
    NSMutableArray *highPoints = [NSMutableArray array];
    
    NSInteger min = 0,max = 0,avg = 0;
    
    for (NSDictionary *dic in low) {
        min = MIN(min, ceil([dic[@"y"]floatValue]));
        max = MAX(max, ceil([dic[@"y"]floatValue]));
    }
    
    for (NSDictionary *dic in middle) {
        min = MIN(min, ceil([dic[@"y"]floatValue]));
        max = MAX(max, ceil([dic[@"y"]floatValue]));
    }
    
    for (NSDictionary *dic in high) {
        min = MIN(min, ceil([dic[@"y"]floatValue]));
        max = MAX(max, ceil([dic[@"y"]floatValue]));
    }
    
    min = floor(min);
    max = ceil(max);
    
    avg = ceil((max-min)*1.f/(5-1));
    
    for (NSDictionary *dic in low) {
        NSInteger index = [low indexOfObject:dic];
        CGPoint p = CGPointMake(index, [dic[@"y"]floatValue]/avg+0.01);
        [lowPoints addObject:NSStringFromCGPoint(p)];
        
        [xAsis addObject:[NSString stringWithFormat:@"%@w",dic[@"x"]]];
    }
    
    for (NSDictionary *dic in middle) {
        NSInteger index = [middle indexOfObject:dic];
        CGPoint p = CGPointMake(index, [dic[@"y"]floatValue]/avg+0.01);
        [middlePoints addObject:NSStringFromCGPoint(p)];
    }
    
    for (NSDictionary *dic in high) {
        NSInteger index = [high indexOfObject:dic];
        CGPoint p = CGPointMake(index, [dic[@"y"]floatValue]/avg+0.01);
        [highPoints addObject:NSStringFromCGPoint(p)];
    }
    
    [yAsis addObject:[NSString stringWithFormat:@"%dkg",min]];
    [yAsis addObject:[NSString stringWithFormat:@"%dkg",min+avg]];
    [yAsis addObject:[NSString stringWithFormat:@"%dkg",min+avg*2]];
    [yAsis addObject:[NSString stringWithFormat:@"%dkg",min+avg*3]];
    [yAsis addObject:[NSString stringWithFormat:@"%dkg",min+avg*4]];
    
    CurveLine *line1 = [[CurveLine alloc]init];
    CurveLine *line2 = [[CurveLine alloc]init];
    CurveLine *line3 = [[CurveLine alloc]init];
    gv.xAsis = xAsis;
    gv.yAsis = yAsis;
    line1.points = lowPoints;
    line1.lineColor = GET_COLOR(@"5dc9e6");
    line2.points = middlePoints;
    line2.lineColor = GET_COLOR(@"30b83c");
    line3.points = highPoints;
    line3.lineColor = GET_COLOR(@"ff2222");
    gv.data = @[line1,line2,line3];
    

    
    UILabel *hightLab = [[UILabel alloc]initWithFrame:CGRectMake(10, gv.frame.origin.y+gv.frame.size.height+1.5, sv.frame.size.width-20, 15)];
    hightLab.textAlignment = NSTextAlignmentCenter;

    NSMutableAttributedString *chartStr = [[NSMutableAttributedString alloc]initWithString:@"▪︎最高值 ▪︎中间值 ▪︎最低值"];
    [chartStr addAttribute:NSForegroundColorAttributeName value:GET_COLOR(@"ff2222") range:NSMakeRange(0, 5)];
    [chartStr addAttribute:NSForegroundColorAttributeName value:GET_COLOR(@"30b83c") range:NSMakeRange(6, 5)];
    [chartStr addAttribute:NSForegroundColorAttributeName value:GET_COLOR(@"5dc9e6") range:NSMakeRange(12, 5)];
    [chartStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, chartStr.length)];
    hightLab.attributedText = chartStr;
    [sv addSubview:hightLab];
    

    NSDictionary *dic1 = arr[1];
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, hightLab.frame.origin.y+hightLab.frame.size.height, /*sv.frame.size.width-20*/100, 20)];
    lab.textAlignment = NSTextAlignmentLeft;
    lab.font = [UIFont systemFontOfSize:13];
    lab.text = @"当前体重增长：";
    [sv addSubview:lab];
    
    UILabel *growValueLab = [[UILabel alloc]initWithFrame:CGRectMake(lab.frame.origin.x + lab.frame.size.width, lab.frame.origin.y, 100, 20)];
    growValueLab.textAlignment = NSTextAlignmentLeft;
    growValueLab.font = [UIFont systemFontOfSize:13];
    growValueLab.text = [NSString stringWithFormat:@"%@kg",dic1[kGrow]];
    [sv addSubview:growValueLab];
    
    UILabel *growDetailLab = [[UILabel alloc]initWithFrame:CGRectMake(10, lab.frame.origin.y+lab.frame.size.height,sv.frame.size.width-20, 20)];
    growDetailLab.textAlignment = NSTextAlignmentLeft;
    growDetailLab.font = [UIFont systemFontOfSize:13];
    growDetailLab.text = dic1[kText];
    [sv addSubview:growDetailLab];
    
    NSArray *leftRows = @[@" 孕前BMI",@" 孕1-12周",@" 孕13周以后",@" 建议孕期增重总值"];
    NSArray *rightRows = @[[NSString stringWithFormat:@" <18.5%@/m²",APP_WEIGHT_UNIT],[NSString stringWithFormat:@" 0.5-2%@",APP_WEIGHT_UNIT],[NSString stringWithFormat:@" 0.45-0.59%@/周",APP_WEIGHT_UNIT],[NSString stringWithFormat:@" 12.7-18.2%@",APP_WEIGHT_UNIT]];
    CGFloat cellOriginY = growDetailLab.frame.origin.y+growDetailLab.frame.size.height+10;
    CGFloat cellWidth = (sv.frame.size.width-20)/2;
    CGFloat cellHeight = 30.f;
    for (int i = 0; i < leftRows.count; i++) {
        UILabel *leftLab = [[UILabel alloc]initWithFrame:CGRectMake(10, cellOriginY+i*(cellHeight-1), cellWidth, cellHeight)];
        leftLab.font = [UIFont systemFontOfSize:13];
        leftLab.text = leftRows[i];
        leftLab.layer.borderWidth = 1.f;
        [sv addSubview:leftLab];
        UILabel *rightLab = [[UILabel alloc]initWithFrame:CGRectMake(10+cellWidth-1, cellOriginY+i*(cellHeight-1), cellWidth, cellHeight)];
        rightLab.font = [UIFont systemFontOfSize:13];
        rightLab.text = rightRows[i];
        rightLab.layer.borderWidth = 1.f;
        [sv addSubview:rightLab];
    }
    [sv setContentSize:CGSizeMake(sv.frame.size.width, 35+170+sv.frame.size.height-160)];
}

#pragma mark 初始化孕前或后相应文字说明
- (void)initBeforeOrAfter:(NSDictionary*)dic
{
    if (!dic) {
        return;
    }
    UILabel *standardLab = [[UILabel alloc]initWithFrame:CGRectMake(10,NAVIGATIONBAR_HEIGHT + 15, 140, 30)];
    standardLab.font =  [UIFont systemFontOfSize:15];
    standardLab.textColor = GET_COLOR(@"3e3e3e");
    standardLab.text = @"标准体重:";
    UILabel *standardValueLab = [[UILabel alloc]initWithFrame:CGRectMake(150,NAVIGATIONBAR_HEIGHT + 15, 100, 30)];
    standardValueLab.font = [UIFont systemFontOfSize:15];
    standardValueLab.textColor = GET_COLOR(@"fe8cb6");
    standardValueLab.text = [NSString stringWithFormat:@"%@kg",dic[kStandardWeight]];
    
    UILabel *currentLab = [[UILabel alloc]initWithFrame:CGRectMake(10, NAVIGATIONBAR_HEIGHT + 60, 140, 30)];
    currentLab.font =  [UIFont systemFontOfSize:15];
    currentLab.textColor = GET_COLOR(@"3e3e3e");
    currentLab.text = @"当前体重:";
    UILabel *currentValueLab = [[UILabel alloc]initWithFrame:CGRectMake(150, NAVIGATIONBAR_HEIGHT + 60, 100, 30)];
    currentValueLab.font = [UIFont systemFontOfSize:15];
    currentValueLab.textColor = GET_COLOR(@"fe8cb6");
    currentValueLab.text = [NSString stringWithFormat:@"%@kg",dic[kCurrentWeight]];
    
    UILabel *controlLab = [[UILabel alloc]initWithFrame:CGRectMake(10, NAVIGATIONBAR_HEIGHT + 105, 140, 30)];
    controlLab.font =  [UIFont systemFontOfSize:15];
    controlLab.textColor = GET_COLOR(@"3e3e3e");
    controlLab.text = @"需控制体重:";
    UILabel *controlValueLab = [[UILabel alloc]initWithFrame:CGRectMake(150, NAVIGATIONBAR_HEIGHT + 105, 100, 30)];
    controlValueLab.font = [UIFont systemFontOfSize:15];
    controlValueLab.textColor = GET_COLOR(@"fe8cb6");
    controlValueLab.text = [NSString stringWithFormat:@"%@kg",dic[kControlWeight]];
    
    UILabel *noticLab = [[UILabel alloc]initWithFrame:CGRectMake(10, NAVIGATIONBAR_HEIGHT + 150, 300, 30)];
    noticLab.font = [UIFont systemFontOfSize:15];
    noticLab.textColor = GET_COLOR(@"3e3e3e");
    noticLab.text = @"建议通过合理饮食和运动达到理想体重";
    
    [self.view addSubview:standardLab];
    [self.view addSubview:standardValueLab];
    [self.view addSubview:currentLab];
    [self.view addSubview:currentValueLab];
    [self.view addSubview:controlLab];
    [self.view addSubview:controlValueLab];
    [self.view addSubview:noticLab];
}

#pragma mark 加载数据
-(void)loadData
{
    CLog(@"获取理想体重数据");
    
    NSMutableDictionary *dic= [NSMutableDictionary dictionary];
    [dic setValue:@"weightManage" forKeyPath:IOS_METHOD_NAME];
    [dic setValue:APP_USER_MSG.id forKeyPath:kUserID];
    
    [LoadingFrameView showLoadingview];
    
    ASIHTTPRequest *request =  [NetUtls httpGet:self withValue:dic tag:IOS_WEIGHT_TAG need:YES];
    [request startAsynchronous];
    
    if (!CURRENT_NETWORK_STATE) {
        [LoadingFrameView directlyDisappear];

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *cache = [userDefaults dictionaryForKey:WEIGHT_REFERENCE_KEY];
        [self loadMainView:cache];
    }
}

-(void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%d:%@",request.tag,[request responseString]);
    NSDictionary *dic = [[request responseString] objectFromJSONString];
    
    //获取历史数据
    if (dic != nil) {
        [self loadMainView:dic];
        
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:dic forKey:WEIGHT_REFERENCE_KEY];
        [userDefault synchronize];
        
    }else{
        [self requestFailed:request];
    }
    
    [LoadingFrameView directlyDisappear];
    
}

- (void)loadMainView:(NSDictionary*)dic
{
    NSString *pregnncy = dic[kPregnancy];
    NSDictionary *weightDic = dic[kWeight];
    NSLog(@"weight:%@,grow:%@,text:%@",weightDic,weightDic[kGrow],weightDic[kText]);
    //        pregnncy = @"2";
    if (pregnncy) {
        NSInteger index = [pregnncy integerValue];
        switch (index) {
            case 1:case 3:
            {
            [self initBeforeOrAfter:dic[kDatas]];
            }
                break;
            case 2:
            {
            [self initChart:@[dic[kDatas],dic[kWeight]]];
            }
                break;
            default:
                break;
        }
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    [LoadingFrameView autoDisappearBlockingview:[NSString stringWithFormat:@"获取%d失败",request.tag]];
}

-(void)leftButtonClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

@end
